package com.fingerth.myjsondemo.controller;

import com.fingerth.myjsondemo.PictureRepository;
import com.fingerth.myjsondemo.tab.Picture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

@RestController
@RequestMapping("test")
public class PicController {

    @Autowired
    PictureRepository picRepository;

    @PostMapping("uploadpic")
    public String uploadPic(@RequestParam("file") MultipartFile image, @RequestParam("file2") MultipartFile image2, @RequestParam("id") String id) {

        String imgName = UUID.randomUUID().toString().replace("_", "").replace("-", "") + "_" + image.getOriginalFilename().replaceAll(" ", "");
        //保存图片
        String imgFilePath = "D://img/" + imgName;
        OutputStream out = null;
        try {
            out = new FileOutputStream(imgFilePath);
            out.write(image.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        return imgName;
    }

    @PostMapping("uploadpic2")
    public String uploadPic(MultipartRequest images, HttpServletRequest request, @RequestParam("id") String id) {
        //Date date = new Date().getTime();
        String dateStr = new SimpleDateFormat("yyyyMMddHHmm", Locale.getDefault()).format(new Date());
        Map<String, MultipartFile> map = images.getFileMap();
        AtomicBoolean success = new AtomicBoolean(false);
        AtomicReference<String> ids = new AtomicReference<>("");
        map.forEach((key, value) -> {
//            String[] split = Objects.requireNonNull(value.getOriginalFilename()).split("\\.");
//            String suffix = "jpg";
//            if (split.length > 0) {
//                suffix = split[split.length - 1];
//            }
            String imgName = dateStr + "_" + UUID.randomUUID().toString().replace("_", "").replace("-", "");//+ "." + suffix;

            //保存图片
            String imgFilePath = "D://img/" + imgName;
            OutputStream out = null;
            try {
                out = new FileOutputStream(imgFilePath);
                out.write(value.getBytes());

                String w = request.getParameter(key + "With");
                String h = request.getParameter(key + "Height");

                Picture pic = new Picture(imgName, w, h, 1);
                Picture p = picRepository.save(pic);
                ids.updateAndGet(v -> v + "," + p.id);
                success.set(true);
            } catch (Exception e) {
                e.printStackTrace();
                success.set(false);
            } finally {
                if (out != null) {
                    try {
                        out.flush();
                        out.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        if (success.get()) {
            return "{\"result\":0,\"msg\":\"success\",\"id\":\"" + ids.get().replaceFirst(",", "") + "\"}";
        } else {
            return "{\"result\":1,\"msg\":\"error\"}";
        }
    }

}
